<template>
  <div class="add_editor_article">
    <div class="article">
      <div class="title">{{ this.articleId ? "修改文章" : "新建文章" }}</div>
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane name="base" label="基本属性">
          <Base
            ref="base"
            v-bind:articleForm.sync="articleForm"
            v-bind.sync="articleForm"
            :channelId="channelId"
            :siteId="siteId"
            @changeYigaoduotouId="changeYigaoduotouId"
            @changeBiaotiTupian="changeBiaotiTupian"
            :showMessage="showMessage"
            :showDsfb="showDsfb"
          >
          </Base>
        </el-tab-pane>
        <el-tab-pane name="file" label="附件">
          <File
            v-bind:articleForm.sync="articleForm"
            v-bind.sync="articleForm"
            v-bind:historyAttr.sync="historyAttr"
          ></File>
          <!-- <File v-bind:articleForm.sync='articleForm' v-bind:attachment.sync='articleForm.attachment'></File> -->
        </el-tab-pane>
        <el-tab-pane name="three" label="图片" v-if="false">
          <Picture v-bind:articleForm.sync="articleForm"></Picture>
        </el-tab-pane>
        <el-tab-pane name="four" label="音视频" v-if="false">
          <Video v-bind:articleForm.sync="articleForm"></Video>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-row
      :gutter="10"
      class="grid-content btn_wrap_bottom"
      type="flex"
      justify="end"
    >
      <el-col :span="1.5" v-if="false">
        <!-- <el-button type="cyan" round @click="handleHelp">帮助</el-button> -->
        <!-- <el-button type="warning" icon="el-icon-warning" circle></el-button> -->
        <el-tooltip
          class="item"
          effect="dark"
          content="帮助"
          placement="top-start"
        >
          <i
            class="el-icon-warning"
            style="color: #f5a300; fontsize: 36px"
            @click="handleHelp"
          ></i>
        </el-tooltip>
      </el-col>

      <el-col :span="1.5" v-if="this.articleId">
        <el-popover
          placement="top-start"
          class="popover"
          width="500"
          trigger="click"
          ref="popover"
          @show="getListArticleWorkFlow"
        >
          <p style="fontsize: 24px">文章状态记录及点评意见</p>
          <h3 style="margin-bottom: 4px">
            <font color="red">文章文件状态记录日志：</font>
          </h3>
          <el-timeline>
            <el-timeline-item
              v-for="(item, k) in articleWorkFlowList"
              :key="item.id"
              :timestamp="k + 1 + '. ' + item.createdDate"
              placement="top"
            >
              <h4>
                用户[<font color="red">{{ item.loginId }}</font> ]
                =>执行操作<font color="red">{{ item.info }}</font>
              </h4>
              <p>
                捎带意见：
                <font color="red">{{ item.oneMessage || "无" }}</font>
              </p>
            </el-timeline-item>
          </el-timeline>
          <font color="red" v-if="articleWorkFlowList.length == 0">
            此文章没有相关记录！
          </font>
          <el-button
            slot="reference"
            type="text"
            icon="el-icon-question"
            size="mini"
            >文章状态记录及点评意见</el-button
          >
          <!-- <el-tooltip class="item" effect="dark" content="文章状态记录及点评意见" placement="top">
            <i class="el-icon-info" style="color:#909399;fontSize: 36px" v-popover:popover></i>
          </el-tooltip> -->
        </el-popover>
      </el-col>
      <el-col :span="1.5">
        <el-button type="cyan" round @click="handleCacle">关闭</el-button>
        <!-- <el-button type="info" icon="el-icon-star-off" circle></el-button> -->
        <!-- <i class="el-icon-info" style="color: #f5a300 ;fontSize: 36px" @click="handleCacle"></i> -->
      </el-col>

      <el-col :span="1.5" v-for="(item, index) in buttonList" :key="index">
        <el-button :type="item.type" round @click="handleClickButton(item)"
          >{{ item.name }}
        </el-button>
      </el-col>

      <el-col :span="1.5" v-if="buttonList.length == 0"> 没有其他按钮 </el-col>
    </el-row>
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="dialogOneMessage"
      width="600px"
    >
      {{ subTitle }}
      <el-input
        type="textarea"
        :rows="8"
        placeholder="请输入内容"
        v-model="oneMessage"
      ></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogOneMessage = false">取 消</el-button>
        <el-button type="primary" @click="sureShaodai">{{
          buttonStr
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Base from "./components/base";
import File from "./components/file";
import Picture from "./components/picture";
import Video from "./components/video";
import { articleViewUrl } from "@/api/content/mywork";
import { isString } from "@/utils/validate.js";
import {
  getArticleInfo,
  editArticle,
  addArticle,
  getButtonForEdit,
  getButtonForAdd,
  getArticleWorkFlowList,
  getIsonymArticleList,
  refreshUserEditStatus,
  duplicateSubmissionList,
  getWebDomain,
  getArticleCache,
  setArticleCache,
  articleRemove,
  deleteArticleFiles,
} from "@/api/content/article";
import { deepClone, toBool } from "@/utils";
import auth from "@/plugins/auth";
import { validHttp } from "@/utils/validate";
import { mapState } from "vuex";

export default {
  metaInfo() {
    return {
      title: this.articleId ? "修改文章" : "新建文章",
      titleTemplate: (title) => {
        return title;
      },
    };
  },
  props: {},
  data() {
    return {
      //tab 标签
      activeName: null,
      articleId: this.$route.query.articleId,
      channelId: this.$route.query.channelId,
      siteId: this.$route.query.siteId,
      siteAlias: this.$route.query.siteAlias,
      workflowId: this.$route.query.workflowId,
      articleForm: {},
      articleFormOther: {
        oneMessage: undefined,
        ifSaveForA: undefined,
        isBackSetp: undefined,
        contributeToOtherChannelId: undefined,
      },

      //捎带信息对话框
      dialogOneMessage: false,
      title: null,
      // 请审核  请修改  请发布
      oneMessageType: null,
      //捎带信息  没有双向绑定
      oneMessage: null,
      //文章审核记录
      articleWorkFlowList: [],
      //文章相同重复列表
      isonymArticleList: [],
      //编辑  添加  按钮列表
      buttonList: [],
      //计时器
      timer: null,

      contributeToOtherChannelId: undefined,
      yigaoduotouId: {
        contributeToOppositeChannelId: undefined,
        contributeToOtherChannelId: undefined,
        contributeToSxChannelId: undefined,
        contributeToWChannelId: undefined,
        contributeToZSDWWChannelId: undefined,
      },
      //提交文章类型
      buttonType: {},
      //历史文件
      historyAttr: [],

      // base 表单验证
      showMessage: true,
      // 系统参数，是否自动保存文档
      articleAutoAave: false,
      //计时器
      timer_articleAutoAave: null,
      // 通过editBtn 是否有定时发布按钮再显示
      showDsfb: false,
    };
  },

  components: { Base, File, Picture, Video },

  computed: {
    subTitle() {
      let str;
      switch (this.oneMessageType) {
        case 0:
          str = "请审核";
          break;
        case 1:
          str = "请修改";
          break;
        case 2:
          str = "请发布";
          break;
        default:
          str = "请审核";
          break;
      }
      return str;
    },
    buttonStr() {
      let str;
      switch (this.oneMessageType) {
        case 1:
          str = "退 回";
          break;
        case 2:
          str = "发 布";
          break;
        case 3:
          str = "同 意";
          break;
        default:
          str = "确 定";
          break;
      }
      return str;
    },
    ...mapState({
      city_name: (state) => state.user.city_name,
    }),
  },
  async created() {},
  async mounted() {
    await this.getConfigKey("article_auto_save").then((response) => {
      // Boolean('false') = true
      this.articleAutoAave = toBool(response.msg);
      console.log(
        "🚀 ~ file: add_editor_article.vue ~ line 167 ~ awaitthis.getConfigKey ~ this.articleAutoAave ",
        this.articleAutoAave
      );

      this.$nextTick(async () => {
        // this.getArticleDetail();
        this.articleId ? await this.getArticleDetail2() : await this.reset();

        console.log("this.$refs.base.visible: ", this.$refs.base.visible);
        console.log("this.articleForm: ", this.articleForm);
        this.$refs.base.change1(1);
        this.timer_articleAutoAave =
          this.articleAutoAave &&
          setInterval(() => {
            this.handleSetArticleCache();
          }, 10000);
      });
    });
  },

  watch: {
    // articleId: {
    //   handler(val) {
    //     console.log("val: ", val);
    //     this.$nextTick(() => {
    //       val ? this.getArticleDetail2() : this.reset();
    //       //createTime 默认new date的话，选择会报错。。
    //       this.$refs.base.change1(1);
    //     });
    //   },
    //   immediate: true,
    // },
  },

  methods: {
    //文章审核记录
    getListArticleWorkFlow() {
      this.articleId &&
        getArticleWorkFlowList({ articleId: this.articleId }).then((res) => {
          this.articleWorkFlowList = res.data;
        });
    },
    getAddButton() {
      getButtonForAdd({ channelId: this.channelId }).then((res) => {
        this.buttonList = res.data.map((item) => {
          item.workflowStatuId = item.workflowStatusId;
          return item;
        });
      });
    },
    getEditButton() {
      let hasROle = auth.hasRole("dsfb");

      getButtonForEdit({ articleId: this.articleId }).then((res) => {
        // res.data.map((item) => {
        //   item.workflowStatuId = item.workflowStatusId;
        //   return item;
        // });
        this.buttonList = res.data.filter((item) => {
          item.workflowStatuId = item.workflowStatusId;
          if (item.workflowStatuId == 9999999) this.showDsfb = true;
          return hasROle ? item : item.workflowStatuId !== 9999999;
        });
      });
    },
    //获取文章内容  先获取文章缓存  暂时不用了
    getArticleDetail() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      this.articleId &&
        getArticleInfo({ articleId: this.articleId })
          .then((res) => {
            res.data.dept0 ||= null;
            res.data.dept2 ||= null;
            res.data.dept3 ||= null;
            res.data.dept4 ||= null;
            res.data.dept5 ||= null;
            res.data.dept6 ||= null;
            res.data.dept7 ||= null;
            res.data.dept8 ||= null;
            res.data.body = res.data.body
              ? res.data.body + '<p data-we-empty-p=""><br></p>'
              : "";
            res.data.newAttachment = [];
            this.articleForm = res.data;
            this.historyAttr = deepClone(res.data.attachment);

            console.log("  this.articleForm: ", this.articleForm);
            this.getSiteIdIp();
          })
          .then(() => {
            this.articleId && this.getEditButton();
            console.log("getEditButton: ");
          })
          .then(() => {
            this.articleId &&
              getIsonymArticleList({ articleId: this.articleId }).then(
                (res) => {
                  if (res.data.length > 1) {
                    this.isonymArticleList = res.data;
                    alert("有重名文章");
                    console.log("有重名文章: ");
                  }
                }
              );
          })
          .then(async () => {
            await this.$refs.base.getDepOptiontList();
            await this.$nextTick(() => {
              loading.close();
              this.activeName = "base";
              this.timer = setInterval(() => {
                this.refreshArticleDetail();
              }, 5000);
            });
          });
    },
    //获取文章内容  先获取文章缓存
    async getArticleDetail2() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      new Promise(async (res) => {
        // 如果自动保存。先获取缓存
        if (this.articleAutoAave) {
          //获取缓存
          await this.handleGetArticleCache();
        } else {
          // 获取文章内容
          await this.handleGetArticleDetail();
          console.log("1.先获取文章详情", this.articleForm);
        }

        // 处理电网动态的默认第一个视频
        if (this.city_name == "dwdt") {
          // this.articleForm.body = this.handleDwdtFirstVideo();
          if (this.articleForm.body.toLowerCase().indexOf(".wmv") > -1) {
            this.msgError("文章中存在wmv视频，视频播放失败");
          }
        }

        // 处理标题图片 的 url
        if (
          this.articleForm.imgNews == 1 &&
          this.articleForm.imageCache.length > 0
        ) {
          this.articleForm.imageCache.map((item) => {
            item.url = item.storeName;
            return item;
          });
          this.articleForm.image = [];
          this.$refs.base.visible.biaotitupian = true;
          console.log("this.articleForm: ", this.articleForm);
        }
        res();
      })
        .then((res) => {
          this.getSiteIdIp();
          console.log("2.获取ip");
        })
        .then(() => {
          this.articleId && this.getEditButton();
          console.log("3.获取按钮");
        })
        .then(() => {
          this.articleId &&
            getIsonymArticleList({ articleId: this.articleId }).then((res) => {
              if (res.data.length > 1) {
                this.isonymArticleList = res.data;
                alert("有重名文章");
                console.log("有重名文章: ");
              }
            });
        })
        .then(async () => {
          await this.$refs.base.getDepOptiontList();
          console.log("5.获取部门完成");
          await this.$nextTick(() => {
            loading.close();
            // 需要修改
            this.activeName = "base";
            this.timer = setInterval(() => {
              this.refreshArticleDetail();
            }, 5000);
          });
        });
    },
    // 获取文章详情
    async handleGetArticleDetail() {
      (await this.articleId) &&
        (await getArticleInfo({ articleId: this.articleId }).then((res) => {
          res.data.newAttachment = [];
          res.data.dept1 ||= null;
          res.data.dept2 ||= null;
          res.data.dept3 ||= null;
          res.data.dept4 ||= null;
          res.data.dept5 ||= null;
          res.data.dept6 ||= null;
          res.data.dept7 ||= null;
          res.data.dept8 ||= null;
          res.data.body = res.data.body
            ? res.data.body + '<p data-we-empty-p=""><br></p>'
            : "";
          res.data.workflowStatuIdCache = res.data.workflowStatuId;
          res.data.imageCache = deepClone(res.data.image);
          this.articleForm = res.data;
          this.historyAttr = deepClone(res.data.attachment).sort(
            (item, next) => {
              return item.sequence - next.sequence;
            }
          );
        }));
    },
    /**
     * 处理电网动态的  第一个视频
     * return 拼接好后的视频
     */
    handleDwdtFirstVideo() {
      // 原始字符串
      const str = this.articleForm.body;
      if (str.indexOf("video") > -1 || str.indexOf("embed") > -1) {
        console.log("文章中存在 embed || video 不处理");
        return;
      }
      // 使用正则表达式解析第一个 <a> 标签的 href
      const regex = /<a\s+href="([^"]+)"/;
      const match = str.match(regex);
      if (match) {
        const href = match[1]; // 提取 href 属性值
        console.log("href: ", href);

        const header = this.articleForm.header; // 变量 header
        console.log("header: ", header);
        let newStr = str;
        if (href.includes(header)) {
          const videoSrc = href; // 设置 video 的 src
          console.log("videoSrc: ", videoSrc);

          // 拼接新的字符串   video 标签不能播放。
          newStr = `<p style="text-align: center;">
              <video src="${videoSrc}" controls="controls" style="max-width:100%;" width="80%" class="editor-video editor-big-video"><span>当前浏览器版本过低，无法正常播放视频，请升级您的浏览器。</span>
              </video>
            </p>
            ${str}
          `;
        }
        console.log("newStr: ", newStr); // 输出拼接后的字符串
        return newStr;
      }
    },
    //获取文章缓存
    handleGetArticleCache() {
      getArticleCache({ articleId: this.articleId || null }).then((res) => {
        console.log("res: getArticleCache 文章缓存1111", res);
        if (res.data && res.msg != "缓存不存在") {
          res.data.dept2 ||= null;
          res.data.dept3 ||= null;
          res.data.dept4 ||= null;
          res.data.dept5 ||= null;
          res.data.dept6 ||= null;
          res.data.dept7 ||= null;
          res.data.dept8 ||= null;
          res.data.body ||= "";

          res.data.newAttachment = [];
          if (
            isString(res.data.body) &&
            isString(res.data.header) &&
            isString(res.data.author1)
          ) {
            this.articleForm = res.data;
            console.log("  this.articleForm: ", this.articleForm);
            this.historyAttr = deepClone(res.data.attachment);
          }
        } else {
          this.handleGetArticleDetail();
        }
      });
    },
    // 保存文章缓存
    handleSetArticleCache() {
      this.showMessage = false;

      this.articleForm.dept1 = Array.isArray(this.articleForm.dept1)
        ? this.articleForm.dept1[1]
        : this.articleForm.dept1;
      this.articleForm.dept2 = Array.isArray(this.articleForm.dept2)
        ? this.articleForm.dept2[1]
        : this.articleForm.dept2;
      this.articleForm.dept3 = Array.isArray(this.articleForm.dept3)
        ? this.articleForm.dept3[1]
        : this.articleForm.dept3;
      this.articleForm.dept4 = Array.isArray(this.articleForm.dept4)
        ? this.articleForm.dept4[1]
        : this.articleForm.dept4;
      this.articleForm.dept5 = Array.isArray(this.articleForm.dept5)
        ? this.articleForm.dept5[1]
        : this.articleForm.dept5;
      this.articleForm.dept6 = Array.isArray(this.articleForm.dept6)
        ? this.articleForm.dept6[1]
        : this.articleForm.dept6;
      this.articleForm.dept7 = Array.isArray(this.articleForm.dept7)
        ? this.articleForm.dept7[1]
        : this.articleForm.dept7;
      this.articleForm.dept8 = Array.isArray(this.articleForm.dept8)
        ? this.articleForm.dept8[1]
        : this.articleForm.dept8;
      console.log("this.articleForm: ", this.articleForm);
      setArticleCache(this.articleForm).then((res) => {
        if (res.code == 200) {
          this.msgInfo("缓存保存成功");
        } else {
          this.msgError(res.msg);
        }
      });
    },
    getSiteIdIp() {
      this.articleForm.siteAlias &&
        getWebDomain({ siteAlias: this.articleForm.siteAlias }).then((res) => {
          if (res.code == 200) {
            this.articleForm.ip = `${res.msg}`;
          }
        });
      return;
      this.getDicts("web_domain").then((response) => {
        let ipItem = response.data.find((item) => {
          return item.dictLabel == this.articleForm.siteAlias;
        });
        if (!ipItem) {
          this.msgInfo("请先配置该站点的网站域名后再操作");
          return;
        }
      });
    },
    //刷新文章状态
    refreshArticleDetail() {
      refreshUserEditStatus({ articleId: this.articleId });
    },

    // 帮助
    handleHelp() {
      alert("bangzhu");
    },
    //取消
    handleCacle() {
      this.$confirm("您确定要取消文章编辑吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.closeWindow();
        })
        .catch(() => {
          return;
        });
    },
    dealWith2(item) {
      this.articleForm.workflowStatuId = item.workflowStatuId;
      this.articleFormOther.isBackSetp = 1;
      this.title = "退回意见输入窗口";
      this.oneMessageType = 1;

      this.dialogOneMessage = true;
    },
    dealWith3(item) {
      this.articleForm.workflowStatuId = item.workflowStatuId;
      this.articleFormOther.ifSaveForA = 1;
      this.handleSubmitArticle();
    },
    // 审核人提交
    shrSubmit(item) {
      this.articleForm.workflowStatuId = item.workflowStatuId;
      this.handleSubmitArticle();
    },
    //统一按钮方法
    handleClickButtonNull(item) {
      console.log(
        "🚀 ~ file: add_editor_article.vue:450 ~ handleClickButton ~ item",
        item
      );

      this.articleForm.workflowStatuId = item.workflowStatuId;
      //保存按钮类型。 保存草稿不退出。
      this.buttonType = item;

      if (item.name.indexOf("退回") > -1 || item.name.indexOf("退稿") > -1) {
        this.articleFormOther.isBackSetp = 1;
      }
      // this.articleForm.workflowStatuId = item.workflowStatuId;

      // 定时发布
      if (item.workflowStatuId == 9999999) {
        this.articleForm.workflowStatuId = item.workflowStatuId;
        this.handleSubmitArticle();
        return;
      }

      if (item.name == "保存") {
        // 相当于 旧代码的   dealWith3("+workflowStatuId+",1);
        // 旧代码中 保存  用的是dealWith3 的方法。
        this.dealWith3(item);
        return;
      }
      //源码中有3个dealWith2的方法，还有个  ifOperatorForWFStep 不知道什么意思。不知道有用没。

      if (
        item.name == "退回" &&
        [109, 110, 133].includes(this.articleForm.workflowStatuId)
      ) {
        this.dealWith2(item);
        return;
      }
      //9  11  审核人。不存在  不需要了
      if (item.workflowStatuId == 9 || item.workflowStatuId == 11) {
        //二级审核，需要选择审核人 选择审核人后     最终都要提交文章。
        // this.submitArticle1();
        //应该直接提交就好

        this.shrSubmit(item);
        //应该要判断是否存在 审核人。不存在 让他选择。
      }
      //10  12   审核信息
      //13  14  退回意见
      // else if (
      //   [2, 10, 12, 13, 14, 26, 40, 41, 107].includes(item.workflowStatuId)
      //   // ||        (this.workflowId > 5 && this.articleForm.articleId)  //这个不知道啥时候需要
      // ) {
      //   this.articleForm.workflowStatuId = item.workflowStatuId;
      //   //审核信息输入窗口
      //   // this.submitArticle2();

      //   this.title = "审核信息输入窗口";
      //   if (item.workflowStatuId == 10 || item.workflowStatuId == 12) {
      //     this.title = "审核信息输入窗口";
      //     this.oneMessageType = 3;
      //   } else if (item.workflowStatuId == 13 || item.workflowStatuId == 14) {
      //     this.title = "退回意见输入窗口";
      //     this.oneMessageType = 1;
      //   }
      //   this.dialogOneMessage = true;
      //   return;
      // }

      // -1  删除
      else if (item.workflowStatuId == -1) {
        this.articleForm.workflowStatuId = item.workflowStatuId;
        this.$confirm("您确定要删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.handleSubmitArticle();
          })
          .catch(() => {
            return;
          });
        return;
      }
      // 2  退回
      else if (item.workflowStatuId == 2) {
        // 退回  退回作者按钮  item.workflowStatuId == 2
        //好像还需要判断 $("#workflowId").val()/1>5
        if (![40, 41, 25, 26].includes(this.articleForm.workflowStatuId)) {
          if ([10, 11].includes(this.workflowId)) {
            this.articleForm.workflowStatuId = 41;
          } else if ([6, 7].includes(this.workflowId)) {
            this.articleForm.workflowStatuId = 26;
          }
        }
        this.title = "退回意见输入窗口";
        this.oneMessageType = 1;

        this.dialogOneMessage = true;
        return;
      } else {
        if (this.articleForm.articleId) {
          if (this.workflowId > 5 && item.workflowStatuId > 3) {
            this.title = "意见信息框";
            this.oneMessageType = 0;
            this.dialogOneMessage = true;
          } else {
            this.articleForm.workflowStatuId = item.workflowStatuId;
            this.handleSubmitArticle();
          }
        } else {
          if (
            this.workflowId > 5 &&
            item.workflowStatuId > 1 &&
            item.workflowStatuId != 3
          ) {
            if (item.workflowStatuId == 2) {
              if (
                ![40, 41, 25, 26].includes(this.articleForm.workflowStatuId)
              ) {
                if ([10, 11].includes(this.workflowId)) {
                  this.articleForm.workflowStatuId = 41;
                } else if ([6, 7].includes(this.workflowId)) {
                  this.articleForm.workflowStatuId = 26;
                }
              }
            } else {
              this.articleForm.workflowStatuId = item.workflowStatuId;
              if ([15, 17, 44].includes(this.workflowStatuId)) {
                this.title = "意见信息框";
                this.oneMessageType = 2;
                this.dialogOneMessage = true;
              } else {
                if (this.articleForm.articleId) {
                  this.title = "审核信息输入窗口";
                } else {
                  this.title = "意见信息框";
                }
                this.oneMessageType = 3;
                this.dialogOneMessage = true;
              }
            }
          } else {
            this.articleForm.workflowStatuId = item.workflowStatuId;
            this.handleSubmitArticle();
          }
        }
      }
    },
    handleClickButton(item) {
      this.articleForm.workflowStatuId = item.workflowStatuId;
      // 定时发布
      if (item.workflowStatuId == 9999999) {
        if (!this.articleForm.dsfbsj) {
          this.$alert("请选择定时发布时间", "定时发布", {
            confirmButtonText: "确定",
            callback: (action) => {
              return;
            },
          });
          return;
        }
        this.handleSubmitArticle();
        return;
      }
      if (item.name == "保存") {
        // 相当于 旧代码的   dealWith3("+workflowStatuId+",1);
        // 旧代码中 保存  用的是dealWith3 的方法。
        this.articleFormOther.ifSaveForA = 1;
      }

      // item.workflowStatuId == 9 || item.workflowStatuId == 11  二级流程的时候不需要在文章内部指定发布人。直接在栏目中分配就行
      // 删除
      if (item.workflowStatuId == -1) {
        this.$confirm("您确定要删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            articleRemove({ articleIds: this.articleForm.articleId }).then(
              (res) => {
                if (res.code == 200) {
                  this.msgSuccess("文章删除成功");
                  this.closeWindow();
                }
              }
            );
          })
          .catch(() => {
            return;
          });
        return;
      }
      // 除了这几个按钮  其他都有弹框
      if (
        !["保存", "保存草稿", "发布文章", "标记为待发布", "重新发布"].includes(
          item.name
        )
      ) {
        if (item.sendBack) {
          this.articleFormOther.isBackSetp = 1;
          this.title = "退回意见输入窗口";
          this.oneMessageType = 1;
        } else {
          this.title = "审核信息输入窗口";
          this.oneMessageType = 3;
        }

        this.dialogOneMessage = true;
        return;
      } else {
        this.handleSubmitArticle();
      }
    },

    //提交发布文章
    handleSubmitArticle() {
      console.log("this.articleForm: ", this.articleForm);
      this.articleForm.dept1 = Array.isArray(this.articleForm.dept1)
        ? this.articleForm.dept1[1]
        : this.articleForm.dept1;
      this.articleForm.dept2 = Array.isArray(this.articleForm.dept2)
        ? this.articleForm.dept2[1]
        : this.articleForm.dept2;
      this.articleForm.dept3 = Array.isArray(this.articleForm.dept3)
        ? this.articleForm.dept3[1]
        : this.articleForm.dept3;
      this.articleForm.dept4 = Array.isArray(this.articleForm.dept4)
        ? this.articleForm.dept4[1]
        : this.articleForm.dept4;
      this.articleForm.dept5 = Array.isArray(this.articleForm.dept5)
        ? this.articleForm.dept5[1]
        : this.articleForm.dept5;
      this.articleForm.dept6 = Array.isArray(this.articleForm.dept6)
        ? this.articleForm.dept6[1]
        : this.articleForm.dept6;
      this.articleForm.dept7 = Array.isArray(this.articleForm.dept7)
        ? this.articleForm.dept7[1]
        : this.articleForm.dept7;
      this.articleForm.dept8 = Array.isArray(this.articleForm.dept8)
        ? this.articleForm.dept8[1]
        : this.articleForm.dept8;
      if (
        this.articleForm.imgNews == 0 &&
        this.articleForm.imageCache.length == 0
      ) {
        // const imgRegex =
        //   /<p[^>]*class="[^"]*"[^>]*>(?:\s*<img[^>]*alt="[^"]*"[^>]*>\s*)+<\/p>/gi;
        // const match = this.articleForm.body.match(imgRegex);
        // const parser = new DOMParser();
        // const doc = parser.parseFromString(this.articleForm.body, "text/html");
        let imgDom = document.querySelector(".w-e-text-container img");
        console.dir(imgDom);
        if (imgDom) {
          const firstImg = imgDom.parentElement;
          firstImg.className = "bttp-active";
          console.log(firstImg); // "<p><img src="http://example.com/image.jpg">"
          // let _p = document.createElement("p");
          // _p.innerHTML = firstImg;
          // console.log("_p: ", _p);
          // let _img = _p.childNodes[0];
          // console.log("_img: ", _img);

          let imgAttr = {
            storeName: imgDom.getAttribute("storeName") || "",
            realName: imgDom.getAttribute("realName") || "",
          };
          this.changeBiaotiTupian(imgAttr);
        } else {
          console.log("No img tags found.");
        }
      }
      if (validHttp(this.articleForm.body)) {
        this.$confirm(
          "文章内容中包含IP地址，可能涉及IP泄露问题，确认继续操作吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: false,
          }
        )
          .then(() => {
            this.handleBaocun();
          })
          .catch(() => {
            return;
          });
      } else {
        this.handleBaocun();
      }
    },
    handleBaocun() {
      if (this.$refs.base.articleHeaderCopy) {
        this.$confirm("本栏目下已有此标题的文章存在!是否继续提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            if (this.articleForm.articleId) {
              this.articleEditor();
            } else {
              this.articleAdd();
            }
          })
          .catch(() => {
            this.msgInfo("已取消操作");
          });
      } else {
        if (this.articleForm.articleId) {
          this.articleEditor();
        } else {
          this.articleAdd();
        }
      }
    },
    //workflowStatuId==9 ||11
    submitArticle1() {
      this.articleForm.workflowStatuId = item.workflowStatuId == 9 ? 1 : 2;
      alert("9 || 11||选择审核人 workflowStatuId ==9? 1:2");
    },
    //workflowStatuId==10 ||12
    submitArticle2() {
      this.articleForm.workflowStatuId = item.workflowStatuId == 9 ? 1 : 2;
      alert("审核信息输入窗口");
      this.$prompt("请输入邮箱", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputErrorMessage: "邮箱格式不正确",
      })
        .then(({ value }) => {
          this.$message({
            type: "success",
            message: "你的邮箱是: " + value,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    //workflowStatuId==13 ||14
    submitArticle3() {
      alert("退回意见输入窗口");
    },
    articleAdd() {
      // <!-- 不要乱动文件删除   就这样写 -->
      this.articleForm.attachment = this.articleForm.newAttachment;
      console.log("articleAdd   this.articleForm: ", this.articleForm);
      // this.articleForm.attachment.push(...this.articleForm.newAttachment);
      this.$refs["base"].$refs["articleForm"].validate((valid, obj) => {
        console.log(
          "🚀 ~ file: add_editor_article.vue:620 ~ this.$r validate ~ valid",
          valid,
          obj
        );

        if (valid) {
          addArticle(this.articleForm, this.articleFormOther).then((res) => {
            if (res.code == 200) {
              this.msgSuccess("操作成功");
              localStorage.setItem("articleFlag", true);
              // this.$store.dispatch("article/setFlag", true);
              // this.buttonType.workflowStatuId != 1 && this.closeWindow();
              this.closeWindow();
              return;
              this.articleId = res.articleId;
              if (this.buttonType.name == "预览") {
                this.$nextTick(() => {
                  this.getArticleUrl({ articleId: res.articleId });
                });
              }
            } else {
              this.msgError(res.msg);
            }
          });
        } else {
          for (const key in obj) {
            if (Object.hasOwnProperty.call(obj, key)) {
              const element = obj[key];
              console.log(
                "🚀 ~ file: add_editor_article.vue:651 ~ this.$re ment",
                element
              );
              element.forEach((item) => {
                setTimeout(() => {
                  this.$notify({
                    showClose: true,
                    message: item.message,
                    type: "error",
                    duration: 0,
                    position: "bottom-right",
                  });
                }, 10);
              });
            }
          }
          return false;
        }
      });
    },
    articleEditor() {
      // <!-- 不要乱动文件删除   就这样写 -->

      this.articleForm.attachment = this.articleForm.newAttachment;
      console.log("articleEditor   this.articleForm: ", this.articleForm);
      // this.articleForm.attachment.push(...this.articleForm.newAttachment);
      this.$refs["base"].$refs["articleForm"].validate((valid) => {
        if (valid) {
          // this.articleFormOther.ifSaveForA = 2;
          editArticle(this.articleForm, this.articleFormOther).then((res) => {
            if (res.code == 200) {
              this.msgSuccess("操作成功");
              localStorage.setItem("articleFlag", true);
              // this.$store.dispatch("article/setFlag", true);

              // this.buttonType.workflowStatuId != 1 && this.closeWindow();
              this.closeWindow();
              return;
              if (this.buttonType.name == "预览") {
                // this.$nextTick(() => {
                //   this.articleId = res.articleId;
                // });
                this.$nextTick(() => {
                  this.getArticleUrl({ articleId: this.articleId });
                });
              }
            } else {
              this.msgError(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    //预览
    getArticleUrl(articleId) {
      articleViewUrl(articleId).then((res) => {
        let href = res.msg;
        setTimeout(() => {
          window.open(href, "_blank");
        }, 1000);
      });
    },

    //base 修改一稿多投。用不了。sync
    changeYigaoduotouId(yigaoduotouId) {
      if (yigaoduotouId.siteId == this.siteId) {
        // this.contributeToOtherChannelId = yigaoduotouId.channelIds;
        this.articleFormOther.contributeToOtherChannelId =
          yigaoduotouId.channelIds;
      } else {
        let index =
          this.articleForm.duplicateSubmissionList &&
          this.articleForm.duplicateSubmissionList.findIndex((item) => {
            return item.siteId == yigaoduotouId.siteId;
          });
        if (index > -1) {
          yigaoduotouId.channelIds
            ? this.articleForm.duplicateSubmissionList.splice(
                index,
                1,
                yigaoduotouId
              )
            : this.articleForm.duplicateSubmissionList.splice(index, 1);
        } else {
          this.articleForm.duplicateSubmissionList.push(yigaoduotouId);
        }
      }
    },
    //上传标题图片 后  回调 修改image
    async changeBiaotiTupian(obj) {
      if (this.articleForm.articleId) {
        let imgIds = [];
        this.articleForm.imageCache.forEach((item) => {
          if (item.titleImg == 1 && obj) {
            imgIds.push(item.id);
          }
        });
        console.log("this.articleForm: ", this.articleForm);

        imgIds.length > 0 &&
          (await deleteArticleFiles({
            articleId: this.articleForm.articleId,
            ids: imgIds.join(","),
            type: "image",
          }));
      }
      this.$nextTick(() => {
        if (obj) {
          // let a = {
          //   articleId: this.articleId,
          //   id: null,
          //   realName: obj.realName,
          //   sequence: 0,
          //   storeName: obj.storeName,
          //   titleImg: 1,
          // };
          // this.articleForm.image.push(a);
          this.articleForm.image = [
            {
              articleId: this.articleId,
              id: null,
              realName: obj.realName,
              sequence: 0,
              storeName: obj.storeName,
              url: obj.url,
              titleImg: 1,
            },
          ];
          this.articleForm.imageCache = [
            {
              articleId: this.articleId,
              id: null,
              realName: obj.realName,
              sequence: 0,
              storeName: obj.storeName,
              url: obj.url,
              titleImg: 1,
            },
          ];
          this.articleForm.imgNews = 1;
        } else {
          this.articleForm.image = [];
          this.articleForm.imageCache = [];
          this.articleForm.imgNews = 0;
        }
        console.log("this.articleForm.image: ", this.articleForm);
      });
    },
    sureShaodai() {
      this.articleFormOther.oneMessage = this.oneMessage || this.subTitle || "";
      this.dialogOneMessage = false;
      //提交文章
      this.handleSubmitArticle();
    },
    reset() {
      console.log("this.articleAutoAave:reset ", this.articleAutoAave);
      if (this.articleAutoAave) {
        console.log("this.articleAutoAave: ", this.articleAutoAave);
        getArticleCache().then((res) => {
          // res.data.dept1 == 0 ? (res.data.dept1 = undefined) : "";
          // res.data.dept2 == 0 ? (res.data.dept2 = undefined) : "";
          // res.data.dept3 == 0 ? (res.data.dept3 = undefined) : "";
          // res.data.dept4 == 0 ? (res.data.dept4 = undefined) : "";
          // res.data.dept5 == 0 ? (res.data.dept5 = undefined) : "";
          // res.data.dept6 == 0 ? (res.data.dept6 = undefined) : "";
          // res.data.dept7 == 0 ? (res.data.dept7 = undefined) : "";
          // res.data.dept8 == 0 ? (res.data.dept8 = undefined) : "";

          res.data.dept2 ||= null;
          res.data.dept3 ||= null;
          res.data.dept4 ||= null;
          res.data.dept5 ||= null;
          res.data.dept6 ||= null;
          res.data.dept7 ||= null;
          res.data.dept8 ||= null;
          res.data.body ||= "";

          res.data.newAttachment = [];
          if (
            isString(res.data.body) ||
            isString(res.data.header) ||
            isString(res.data.author1)
          ) {
            this.articleForm = res.data;
            console.log("  this.articleForm: ", this.articleForm);
            this.historyAttr = deepClone(res.data.attachment);
          } else {
            this.articleForm = {
              attachment: [],
              newAttachment: [],
              image: [],
              imageCache: [],
              imgNews: "0",
              loginId: this.$store.getters.loginId,
              operator: this.$store.getters.loginId,
              releaseId: this.$store.getters.loginId,
              userId: this.$store.getters.userId,
              articleId: this.$route.query.articleId,
              channelId: this.channelId,
              workflowId: this.workflowId,
              siteId: this.siteId,
              siteAlias: this.siteAlias,
              workflowStatuId: 1,
              xgsname: null,
              zrbjr: null,
              zyry: null,
              state: 1,
              subheadLocation: 0,
              setTop: 0,
              jump: 0,
              time: null, //排序时间
              duplicateSubmissionList: [], //一稿多投id配置
              createdDate: null,
              expiredDate: this.parseTime(
                new Date("2099-12-31"),
                "{y}-{m}-{d}"
              ),
              expiredDateForIndex: this.parseTime(
                new Date("2099-12-31"),
                "{y}-{m}-{d}"
              ),
              //没用了。
              // contributeToOppositeChannelId: "",
              // contributeToSxChannelId: "",
              // contributeToWChannelId: "",
              // contributeToZSDWWChannelId: "",
              author1: "",
              author2: "",
              author3: "",
              author4: "",
              author5: "",
              author6: "",
              author7: "",
              author8: "",
              body: "",

              dept1: undefined,
              dept2: undefined,
              dept3: undefined,
              dept4: undefined,
              dept5: undefined,
              dept6: undefined,
              dept7: undefined,
              dept8: undefined,
            };
          }
        });
      } else {
        this.articleForm = {
          attachment: [],
          newAttachment: [],
          image: [],
          imageCache: [],
          imgNews: "0",

          loginId: this.$store.getters.loginId,
          operator: this.$store.getters.loginId,
          releaseId: this.$store.getters.loginId,
          userId: this.$store.getters.userId,
          articleId: this.$route.query.articleId,
          channelId: this.channelId,
          workflowId: this.workflowId,
          siteId: this.siteId,
          siteAlias: this.siteAlias,
          workflowStatuId: 1,
          xgsname: null,
          zrbjr: null,
          zyry: null,
          state: 1,
          subheadLocation: 0,
          setTop: 0,
          jump: 0,
          time: null, //排序时间
          duplicateSubmissionList: [], //一稿多投id配置
          createdDate: null,
          expiredDate: this.parseTime(new Date("2099-12-31"), "{y}-{m}-{d}"),
          expiredDateForIndex: this.parseTime(
            new Date("2099-12-31"),
            "{y}-{m}-{d}"
          ),
          //没用了。
          // contributeToOppositeChannelId: "",
          // contributeToSxChannelId: "",
          // contributeToWChannelId: "",
          // contributeToZSDWWChannelId: "",
          author1: "",
          author2: "",
          author3: "",
          author4: "",
          author5: "",
          author6: "",
          author7: "",
          author8: "",
          body: "",
          header: "",
          dept1: undefined,
          dept2: undefined,
          dept3: undefined,
          dept4: undefined,
          dept5: undefined,
          dept6: undefined,
          dept7: undefined,
          dept8: undefined,
        };
      }

      this.getAddButton();
      this.getSiteIdIp();
      this.$nextTick(() => {
        this.$refs.base.getDepOptiontList();
        this.activeName = "base";
      });
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  },
};
</script>

<style scoped lang="scss">
@import "~@/assets/styles/el-form.scss";

.add_editor_article {
  width: 80%;
  min-width: 1200px;
  margin: 0 auto;
  height: 100vh;
  position: relative;
  // overflow: overlay;  overflow: auto;

  .btn_wrap_bottom {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 1000;
    margin-bottom: 0;
    height: 64px;
    justify-content: center;
    align-items: center;
    border-top: 1px solid #e8e8e8;
  }

  .article {
    padding: 40px 0 80px;
    height: 100%;
    position: relative;

    .title {
      height: 40px;
      line-height: 40px;
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      color: #000;
      font-weight: bold;
      text-align: center;
      font-size: 20px;
    }
  }
}

// ::v-deep .el-row {
//   border: 1px solid #000;
//   margin-bottom: -1px !important;
// .el-col {
//   border-right: 1px solid #000;
// }
// .el-col:last-child {
//   border-right: none;
// }
// }

// ::v-deep .el-form-item {
//   margin-bottom: 0px !important;
// }
// ::v-deep .article-base .w-e-text-container .w-e-text {
//   table td,
//   table th {
//     border: 1px solid #000 !important;
//   }
// }

::v-deep .el-tabs {
  display: flex;
  flex-direction: column;
  .el-tabs__content {
    overflow: auto;
    flex: 1;
  }
}
</style>
<style>
#app {
  height: auto;
  min-height: 100% !important;
  overflow: inherit;
}
::v-deep .el-popover {
  padding-top: 0;
  height: auto;
}
.el-timeline {
  height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
